package cz.none.bezbarier.web.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import cz.none.bezbarier.web.form.UserControllForm;
import cz.none.bezbarier.web.form.UserForm;
import cz.none.bezbarier.web.model.Role;
import cz.none.bezbarier.web.model.User;
import cz.none.bezbarier.web.repository.UserRepository;
import cz.none.bezbarier.web.security.StaticSaltSource;
import cz.none.bezbarier.web.service.UserService;

@Service
public class UserServiceImpl extends BaseServiceImpl<UserForm, User, String> implements UserService {

	@Autowired
	private UserRepository repository;

	@Autowired
	private StaticSaltSource saltSource;

	@Autowired
	private PasswordEncoder encoder;


	@Override
	public List<User> getAllUsers() {
		return repository.findAll();
	}

	@Override
	public void registerUser(UserForm form) {

		User user = new User();
		user.setActive(false);
		user.setEmail(form.getEmail());
		user.setLocked(false);
		user.setName(form.getName());
		user.setPassword(encoder.encodePassword(form.getPassword1(), saltSource.getSalt(null)));
		user.setRole(Role.AUTHORIZED);
		user.setSurname(form.getSurname());

		repository.save(user);
	}

	@Override
	public boolean deleteUser(String userId) {
		if (repository.exists(userId)) {
			repository.delete(userId);
			return true;
		}

		return false;

	}

	@Override
	public User getCurrentUser() {
		String userName = SecurityContextHolder.getContext().getAuthentication().getName();
		return repository.findUserByEmail(userName);
	}

	@Override
	public void updateUser(UserControllForm form) {
		User user = repository.findOne(form.getId());

		if (null == user) {
			throw new IllegalArgumentException("Bad user id");
		}

		user.setRole(form.getRole());
		user.setActive(form.getActive());
		user.setLocked(form.getLocked());

		repository.save(user);

	}

	@Override
	protected JpaRepository<User, String> getRepository() {
		return repository;
	}

}
